package com.youyiwen.Controller;

import com.youyiwen.Bean.Notice;
import com.youyiwen.Bean.Reply;
import com.youyiwen.Bean.User;
import com.youyiwen.Mapper.CommentMapper;
import com.youyiwen.Mapper.NoticeMapper;
import com.youyiwen.Mapper.QuestionMapper;
import com.youyiwen.Mapper.ReplyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author: zhaoyang
 * @Date: 2021/04/03
 */

@Controller
public class ReplyController {

    @Autowired
    private ReplyMapper replyMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private NoticeMapper noticeMapper;

    @Value("${question.url}")
    String questionUrl;

    @PostMapping("/reply/{id}/{parentId}")
    public String reply(@PathVariable(value = "id") String id,
                        @PathVariable(value = "parentId") String parentId,
                        Model model,
                        HttpServletRequest request) {
        Reply reply = new Reply();

        User user = (User) request.getSession().getAttribute("loginUser");
        if (user == null){
            model.addAttribute("msg","请先登录才能回复");
            return "login";
        }
        String userName = user.getUserName();
        Long current = System.currentTimeMillis();
        String commentArea = id + "Area";
        String content = request.getParameter(commentArea);
        Long gmtCreate = current;
        String replyId = "reply" + current;
        //Bean赋值
        reply.setContent(content);
        reply.setGmtCreate(gmtCreate);
        reply.setId(replyId);
        //父级ID为该id
        reply.setParentId(id);
        reply.setUserName(userName);
        replyMapper.insertReply(reply);

        String commentUserName = commentMapper.selectCommentUserName(id);
        //添加通知
        if (userName != commentUserName)
        {
            String title = questionMapper.selectTitleById(parentId);
            String noticeContent = userName + " 回复了您的评论：";
            Notice notice = new Notice();
            notice.setId(userName + "Notice" + current);
            notice.setContent(noticeContent);
            notice.setTitle(title);
            notice.setQuestionUrl(questionUrl + parentId);
            notice.setUserName(commentUserName);
            notice.setType(2);
            notice.setHasRead(0);
            notice.setGmtCreate(current);
            notice.setParentId(replyId);
            noticeMapper.insertNotice(notice);
        }
        return "redirect:/question/{parentId}";
    }

}
